package cn.liccshop.core.service.shopCategory.service;

import cn.liccshop.core.entity.ShopAttribute;
import cn.liccshop.core.entity.ShopCategory;
import cn.liccshop.core.entity.ShopGoods;
import cn.liccshop.core.service.shopAttribute.mapper.ShopAttributeMapper;
import cn.liccshop.core.service.shopCategory.mapper.ShopCategoryMapper;
import cn.liccshop.core.service.shopCategory.service.IShopCategoryService;
import cn.liccshop.core.service.shopGoods.mapper.ShopGoodsMapper;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.exception.MySystemException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品分类表（就是页面导航栏） 服务实现类
 * </p>
 *
 * @author LiCC
 * @since 2019-04-08
 */
@Service
public class ShopCategoryServiceImpl extends ServiceImpl<ShopCategoryMapper, ShopCategory> implements IShopCategoryService {

    /**
     * 前端树组件ID初始值
     */
    private final int DIALOG_ID = 1;
    private final byte SHOW_IN_NAV = 1;
    private final byte DISPLAY = 1;

    @Autowired
    private ShopAttributeMapper shopAttributeMapper;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Override
    public ShopCategory saveShopCategory(ShopCategory shopCategory, List<ShopAttribute> shopAttributes) {
        /** categories的数据是依照dialog_id字段升序排列的 **/
        shopCategory.setShowInNav(SHOW_IN_NAV).setDisplay(DISPLAY);
        List<ShopCategory> categories = baseMapper.selectList(new QueryWrapper<>(new ShopCategory()).orderByDesc("dialog_id"));
        if (categories == null || categories.size() == 0){
            /** 如果数据库没有数据，组件id赋初始值 **/
            shopCategory.setDialogId(DIALOG_ID);
        } else {
            /** 升序排列 最后一条最大 +1得到最新的dialog_id **/
            shopCategory.setDialogId((categories.get(0).getDialogId()) + 1);
        }
        boolean saveSuccess = retBool(baseMapper.insert(shopCategory));
        if (shopAttributes != null && shopAttributes.size()>0 && saveSuccess){
            /** 如果属性值有数据，并且分类保存成功，继续添加属性数据**/
            for (ShopAttribute attribute : shopAttributes){
                shopAttributeMapper.insert(attribute.setCatId(shopCategory.getId()));
            }
        }
        return saveSuccess ? shopCategory : null;
    }

    @Override
    public ShopCategory updateShopCategory(ShopCategory shopCategory, List<ShopAttribute> shopAttributes) throws MySystemException {
        List<ShopGoods> shopGoods = shopGoodsMapper.selectList(new QueryWrapper<>(new ShopGoods().setCatId(shopCategory.getId())).last("limit 0, 1"));
        List<ShopAttribute> shopAttributeList = shopAttributeMapper.selectList(new QueryWrapper<>(new ShopAttribute().setCatId(shopCategory.getId())));
        if (shopGoods != null && shopGoods.size() > 0){
            /** 该分类有商品数据 **/
            /** 该分类属性就类就是能编辑和添加不能删 **/
            for (ShopAttribute attributeOfDB : shopAttributeList){
                /** 该分类有属性 遍历该分类属性 **/
                boolean isHaveAttirbute = false;
                if (shopAttributes != null && shopAttributes.size()>0) {
                    /** 上传的属性不为空 **/
                    isHaveAttirbute = false;
                    for (ShopAttribute attribute : shopAttributes) {
                        /** 遍历上传的属性 **/
                        if (attributeOfDB.getAttrId().equals(attribute.getAttrId())){
                            /** 上传的属性有该分类属性 **/
                            isHaveAttirbute = true;
                            break;
                        }
                    }
                    if (!isHaveAttirbute){
                        /** 该属性在上传的分类中没有 **/
                        throw new MySystemException("该分类下有商品，不能属性列只能增加和编辑，不能删除！", Constants.SERVICE_FAIL);
                    }
                } else {
                    /** 上传的属性没有值 **/
                    throw new MySystemException("该分类下有商品，不能属性列只能增加和编辑，不能删除！", Constants.SERVICE_FAIL);
                }
            }
        }
        /** 更新节点 **/
        baseMapper.updateById(shopCategory);
        /** 删除该节点下所有属性 **/
        shopAttributeMapper.delete(new QueryWrapper<>(new ShopAttribute().setCatId(shopCategory.getId())));
        /** 添加节点属性 **/
        if (shopAttributes != null && shopAttributes.size()>0){
            for (ShopAttribute attribute : shopAttributes){
                shopAttributeMapper.insert(attribute.setCatId(shopCategory.getId()));
            }
        }
        return shopCategory;
    }

    @Override
    public List<ShopCategory> shopCategoryInfos(ShopCategory shopCategory) throws MySystemException {
        List<ShopCategory> categoriesOfDB = baseMapper.selectList(new QueryWrapper<>(shopCategory).orderByAsc("sort_order"));
        if (categoriesOfDB == null || categoriesOfDB.size() == 0){
            throw new MySystemException("没有找到分类", Constants.SERVICE_FAIL);
        }
        List<ShopCategory> shopCategories = new ArrayList<>();
        for (int i = 0; i < categoriesOfDB.size(); i++){
            /** 第一层开始 **/
            String TopParentId = categoriesOfDB.get(i).getParentId();
            if (StringUtils.isBlank(TopParentId)){
                /** 父ID为空说明是第一层 **/
                ShopCategory categoryTop = categoriesOfDB.get(i);
                List<ShopCategory> topChildren = new ArrayList<>();
                for (int j = 0; j < categoriesOfDB.size(); j ++){
                    /** 第二层开始 **/
                    String secondParentId = categoriesOfDB.get(j).getParentId();
                    if (categoryTop.getId().equals(secondParentId)){
                        /** 第二层父ID与第一层相同 说明是其子分类 **/
                        ShopCategory categorySecond = categoriesOfDB.get(j);
                        List<ShopCategory> secondChildren = new ArrayList<>();
                        for (int k = 0; k < categoriesOfDB.size(); k++){
                            /**第三层开始**/
                            String thirdParentId = categoriesOfDB.get(k).getParentId();
                            if (categorySecond.getId().equals(thirdParentId)){
                                /** 第三层层父ID与第二层相同 说明是其子分类 **/
                                /** 第三层数据保存 **/
                                secondChildren.add(categoriesOfDB.get(k));
                            }
                        }
                        /** 第三层结束 **/
                        /** 第二层数据保存 **/
                        topChildren.add(categorySecond.setChildren(secondChildren));
                    }
                }
                /** 第二层结束 **/
                /** 第一层数据保存 **/
                shopCategories.add(categoryTop.setChildren(topChildren));
            }
        }
        return shopCategories;
    }

    @Override
    public String deleteShopCategory(ShopCategory shopCategory) throws MySystemException {
        List<ShopGoods> shopGoods = shopGoodsMapper.selectList(new QueryWrapper<>(new ShopGoods().setCatId(shopCategory.getId())));
        List<String> ids = new ArrayList<>();
        if (shopGoods != null && shopGoods.size()>0){
            /** 第一层分类下有商品，不能删除 **/
            throw new MySystemException("该分类下有商品，不能删除！", Constants.SERVICE_FAIL);
        }
        /** 第一层分类下没有商品 **/
        /** 查询第二层分类 **/
        List<ShopCategory> shopCategories = baseMapper.selectList(new QueryWrapper<>(new ShopCategory().setParentId(shopCategory.getId())));
        if (shopCategories == null || shopCategories.size() == 0){
            /** 第一层分类下没有商品，没有第二层分类，可以删除 **/
            baseMapper.deleteById(shopCategory.getId());
            return shopCategory.getId();
        }
        /** 有第二层分类 **/
        for (ShopCategory category : shopCategories){
            /** 遍历第二层分类 **/
            /** 查询第二层分类下是否有商品 **/
            List<ShopGoods> shopGoodsSecond = shopGoodsMapper.selectList(new QueryWrapper<>(new ShopGoods().setCatId(category.getId())));
            if (shopGoodsSecond != null && shopGoodsSecond.size()>0){
                /** 第二层分类下有商品，不能删除 **/
                throw new MySystemException("该分类的子分类下有商品，不能删除！", Constants.SERVICE_FAIL);
            }
            /** 第二层分类下没有商品，查询子第三层分类 **/
            List<ShopCategory> shopCategoriesThird = baseMapper.selectList(new QueryWrapper<>(new ShopCategory().setParentId(category.getId())));
            if (shopCategoriesThird != null && shopCategoriesThird.size() >= 0){
                /** 存在第三层 **/
                for (ShopCategory categoryThird : shopCategoriesThird){
                    /** 遍历第三层分类 **/
                    List<ShopGoods> shopGoodsThird = shopGoodsMapper.selectList(new QueryWrapper<>(new ShopGoods().setCatId(categoryThird.getId())));
                    if (shopGoodsThird != null && shopGoodsThird.size()>0){
                        /** 第三层分类下有商品，不能删除 **/
                        throw new MySystemException("该分类的子分类下有商品，不能删除！", Constants.SERVICE_FAIL);
                    }
                    ids.add(categoryThird.getId());
                }
            }
            ids.add(category.getId());
        }
        ids.add(shopCategory.getId());
        baseMapper.deleteBatchIds(ids);
        return shopCategory.getId();
    }

    @Override
    @Transactional
    public Map<String, JSONObject> checkCategoryByCategoryId(String catId) {
        Map<String, List<ShopCategory>> infos = new HashMap<>();
        Map<String, JSONObject> data = new HashMap<>();
        /** 获取该商品分类信息 **/
        ShopCategory categoryThird = baseMapper.selectOne(new QueryWrapper<>(new ShopCategory().setId(catId)));
        /** 获取该商品分类同级分类信息 **/
        List<ShopCategory> categorysThird = baseMapper.selectList(new QueryWrapper<>(new ShopCategory().setParentId(categoryThird.getParentId())).orderByAsc("sort_order"));
        /** 获取该商品父分类信息通过分类父ID **/
        ShopCategory categorySecond = baseMapper.selectOne(new QueryWrapper<>(new ShopCategory().setId(categoryThird.getParentId())));
        /** 获取所有分类信息 **/
        List<ShopCategory> categories = baseMapper.selectList(new QueryWrapper<>(new ShopCategory()).orderByAsc("sort_order"));
        List<ShopCategory> categoriesTop = new ArrayList<>();
        for (ShopCategory category : categories){
            if (StringUtils.isBlank(category.getParentId())){
                /** 父ID为空， 该分类是顶级分类 **/
                categoriesTop.add(category);
            }
        }
        infos.put("topInfos", categoriesTop);
        data.put("topInfos", JSON.parseObject(JSON.toJSONString(infos)));
        if (StringUtils.isNotBlank(categorySecond.getParentId())){
            /** 父分类的父ID不为空，则Top分类存在 **/
            /** 获取该商品父分类同级分类信息 **/
            List<ShopCategory> categorysSecond = baseMapper.selectList(new QueryWrapper<>(new ShopCategory().setParentId(categorySecond.getParentId())).orderByAsc("sort_order"));
            for (ShopCategory categoryTop : categoriesTop){
                if (categoryTop.getId().equals(categorySecond.getParentId())){
                    data.put("topModel",JSON.parseObject(JSON.toJSONString(categoryTop)));
                }
            }

            infos = new HashMap<>();
            infos.put("secondInfos", categorysSecond);
            data.put("secondInfos",JSON.parseObject(JSON.toJSONString(infos)));
            data.put("secondModel",JSON.parseObject(JSON.toJSONString(categorySecond)));

            infos = new HashMap<>();
            infos.put("thirdInfos", categorysThird);
            data.put("thirdInfos",JSON.parseObject(JSON.toJSONString(infos)));
            data.put("thirdModel",JSON.parseObject(JSON.toJSONString(categoryThird)));
        } else {
            for (ShopCategory categoryTop : categoriesTop){
                if (categoryTop.getId().equals(categoryThird.getParentId())){
                    data.put("topModel",JSON.parseObject(JSON.toJSONString(categoryTop)));
                }
            }

            infos = new HashMap<>();
            infos.put("secondInfos", categorysThird);
            data.put("secondInfos",JSON.parseObject(JSON.toJSONString(infos)));
            data.put("secondModel",JSON.parseObject(JSON.toJSONString(categoryThird)));
        }
        return data;
    }
}
